// src/api/index.ts

import { ResultEnum } from "@/enums/httpEnum";
// http://192.168.8.11:8006/
const config = {
  baseURL: "http://192.168.8.26:8081/class",
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials: true // 小程序中 cookie 携带由 header 控制sdf
};

class RequestHttp {
  private config: typeof config;

  constructor(config) {
    this.config = config;
  }

  /**
   * @description 统一请求方法
   */
  request<T>(url: string, method: "GET" | "POST" | "PUT" | "DELETE", data?: any, params?: any): Promise<T> {
    return new Promise((resolve, reject) => {
      console.log("开始请求", data, params);
      uni.showLoading({ title: "加载中..." });
      uni.request({
        url: this.config.baseURL + url,
        method,
        data,
        header: {
          "content-type": method === "POST" ? "application/json" : "application/x-www-form-urlencoded"
        },
        timeout: this.config.timeout,
        success(res: any) {
          uni.hideLoading();
          if (res.statusCode == 200 && res.statusCode < 300) {
            if (res.data.code === ResultEnum.SUCCESS) {
              resolve(res.data.data);
            } else {
              uni.showToast({
                title: res.data.message,
                icon: "none"
              });
              reject();
            }
          } else {
            reject(new Error(`请求失败，状态码：${res.statusCode}`));
          }
        },
        fail(err) {
          console.log("请求失败");
          uni.hideLoading();
          const errorMessage = err.errMsg || "网络错误，请检查网络连接";
          uni.showToast({ title: errorMessage, icon: "none" });
          reject(err);
        }
      });
    });
  }

  // GET 请求
  get<T>(url: string, data?: object): Promise<T> {
    return this.request<T>(url, "GET", data);
  }

  // POST 请求
  post<T>(url: string, data?: object): Promise<T> {
    return this.request<T>(url, "POST", data);
  }

  // PUT 请求
  put<T>(url: string, data?: object): Promise<T> {
    return this.request<T>(url, "PUT", data);
  }

  // DELETE 请求
  delete<T>(url: string, params?: object): Promise<T> {
    return this.request<T>(url, "DELETE", undefined, params);
  }

  // 下载文件（blob）
  download(url: string, data?: object): Promise<BlobPart> {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: this.config.baseURL + url,
        data,
        success(res) {
          if (res.statusCode === 200) {
            resolve(res.tempFilePath);
          } else {
            reject(new Error("下载失败"));
          }
        },
        fail(err) {
          reject(err);
        }
      });
    });
  }
}

export default new RequestHttp(config);
